from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from ..core.database import get_db
from ..core.dependencies import get_current_admin_user
from ..models.user import User
from ..models.department import Department as DepartmentModel
from ..schemas.department import Department, DepartmentCreate, DepartmentUpdate
from ..services.department_service import DepartmentService

router = APIRouter(prefix="/departments", tags=["departments"])

@router.get("/", response_model=List[Department])
def get_departments(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: User = Depends(get_current_admin_user)):
    # 只有管理员可以查看部门列表
    department_service = DepartmentService(db)
    return department_service.get_departments(skip, limit)

@router.post("/", response_model=Department)
def create_department(department: DepartmentCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_admin_user)):
    department_service = DepartmentService(db)
    return department_service.create_department(department)

@router.get("/{department_id}", response_model=Department)
def get_department(department_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_admin_user)):
    # 只有管理员可以查看部门详情
    department_service = DepartmentService(db)
    department = department_service.get_department(department_id)
    if not department:
        raise HTTPException(status_code=404, detail="Department not found")
    return department

@router.put("/{department_id}", response_model=Department)
def update_department(department_id: int, department: DepartmentUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_admin_user)):
    department_service = DepartmentService(db)
    return department_service.update_department(department_id, department)

@router.delete("/{department_id}")
def delete_department(department_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_admin_user)):
    department_service = DepartmentService(db)
    department_service.delete_department(department_id)
    return {"message": "Department deleted successfully"}

@router.get("/stats")
def get_department_stats(db: Session = Depends(get_db), current_user: User = Depends(get_current_admin_user)):
    """获取部门统计信息"""
    department_service = DepartmentService(db)
    return department_service.get_department_stats()